package com.ruoyi.accounts.service.impl;

import java.util.concurrent.ExecutionException;
import org.slf4j.Logger;
import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;
import com.ruoyi.accounts.tcp.WSCommand;
import javax.websocket.Session;
import com.ruoyi.accounts.tcp.WSRespone;
import com.ruoyi.accounts.tcp.GameStateService;
import com.ruoyi.accounts.tcp.GameStateEnum;
import org.slf4j.LoggerFactory;
import java.util.concurrent.TimeUnit;
import org.springframework.stereotype.Service;
import com.ruoyi.accounts.service.base.AbstractClientHandler;

@Service
public class WWJClientHandlerImpl extends AbstractClientHandler{
    
    private static final Logger LOGGER = LoggerFactory.getLogger(WWJClientHandlerImpl.class);

    private GameStateEnum state;

    private final Set<String> supportedCommands = new HashSet<>(
        Arrays.asList("check", "start", "up", "down", "left", "right", "play", "refund")
    );
    
    @Override
    public boolean canHandle(String commandType) {
        return supportedCommands.contains(commandType);
    }
    
    @Override
    public Long getMachineType() {
        return 1L;
    }
    
    @Override
    public void handleCommand(WSCommand command, Session session, String message) throws Exception {
        // 获取state
        state = GameStateService.getGameState(command.getCustomID());
        String commandType = command.getType();
        // 使用switch处理该机器支持的命令
        switch (commandType) {
            case "check":
                handleCheckWWJ(command, session);
                break;
            case "start":
                handleStart(command, session, message);
                break;
            case "up":
                handleUp(command, session, state);
                break;
            case "down":
                handleDown(command, session, state);
                break;
            case "left":
                handleLeft(command, session, state);
                break;
            case "right":
                handleRight(command, session, state);
                break;
            case "play":
                handlePlay(command, session);
                break;
            case "refund":
                handleRefund(command, session);
                break;
            // 其他命令处理...
            default:
                sendMessageToSocketClient(session, false, "娃娃机不支持的命令: " + commandType);
                break;
        }
    }

    private void handleCheckWWJ(WSCommand command, Session session) throws Exception {
        // 实现娃娃机的check处理逻辑
        if (GameStateService.isTakeUp(command.getCustomID(), command.getMachineID())) {
            GameStateEnum gameState = GameStateService.getGameState(command.getCustomID());
            // 不需要再次投币
            if (gameState == GameStateEnum.Playing || gameState == GameStateEnum.Waiting) {
                // 告诉客户端
                sendMessageToSocketClient(session, true, "已投币");
                GameStateService.refresh(command.getCustomID());
                return;
            }
            sendMessageToSocketClient(session, true, "已占机");
        } else {
            LOGGER.info("handleCheckWWJ isTakeUp false");
            sendMessageToSocketClient(session, false, "未占机");
        }
    }

    private void handleStart(WSCommand command, Session session, String message) throws Exception {
        // 实现娃娃机的start处理逻辑
        // 尝试占机
        if (!GameStateService.tryTakeUp(command.getCustomID(), command.getMachineID())) {
            sendMessageToSocketClient(session, false, "机器被占用");
            return;
        }
        /// 判断状态
        // 有游戏状态，可能是断线重连
        GameStateEnum gameState = GameStateService.getGameState(command.getCustomID());
        // 不需要再次投币
        if (gameState == GameStateEnum.Playing || gameState == GameStateEnum.Waiting) {
            // 告诉客户端
            sendMessageToSocketClient(session, true, "重连成功");
            GameStateService.refresh(command.getCustomID());
            return;
        }
        /// 占机成功发送投币消息
        try {
            // 加一个记录，等待投币成功后读取
            stringRedisTemplate.opsForValue().set(command.getCustomID(), message,120, TimeUnit.SECONDS); // 更改状态，投币成功后修改状态为PLAY
            GameStateService.setGameState(command.getCustomID(), GameStateEnum.Waiting);
            sendMessageToSocketClient(session, true, "投币中");
            tcpThreadService.SendStart(command.getCustomID(), command.getMachineID(), command.getCoins());

        } catch (ExecutionException | InterruptedException e) {
            LOGGER.error(e.getMessage());
            sendMessageToSocketClient(session, false, e.getMessage());
        }
    }
    
    private void handlePlay(WSCommand command, Session session) throws Exception {
        // 实现娃娃机的play处理逻辑
        // 下抓
        GameStateService.refresh(command.getCustomID());
        // 判断游戏状态为play
        if (state == null || !state.equals(GameStateEnum.Playing)) {
            sendMessageToSocketClient(session, false, "游戏状态异常");
            return;
        }
        // 发送消息
        try {
            tcpThreadService.SendPLAY(command.getCustomID(), command.getMachineID());
            // 取消定时下抓任务
            GameStateService.cancelTask(command.getCustomID());
            // 删除游戏状态
            GameStateService.removeGameState(command.getCustomID());
            sendMessageToSocketClient(session, true, "成功");
        } catch (Exception e) {
            sendMessageToSocketClient(session, false, e.getMessage());
        }
    }

    // 其他命令处理方法...
}
